import { createStore } from 'vuex'
import axios from 'axios'
import createPersistedState from 'vuex-persistedstate'

export default createStore({
  plugins: [createPersistedState()],
  state: {
    user: null,
    isAuthenticated: false,
    models: [],
    conversations: [],
    currentConversation: null,
    loading: false,
    error: null
  },
  mutations: {
    SET_USER(state, user) {
      state.user = user
      state.isAuthenticated = true
    },
    LOGOUT(state) {
      state.user = null
      state.isAuthenticated = false
      localStorage.removeItem('token')
    },
    SET_MODELS(state, models) {
      state.models = models
    },
    ADD_CONVERSATION(state, conversation) {
      state.conversations.push(conversation)
    },
    SET_CURRENT_CONVERSATION(state, conversation) {
      state.currentConversation = conversation
    },
    ADD_MESSAGE(state, { conversationId, message }) {
      const conversation = state.conversations.find(c => c.id === conversationId)
      if (conversation) {
        conversation.messages.push(message)
      }
    },
    SET_LOADING(state, loading) {
      state.loading = loading
    },
    SET_ERROR(state, error) {
      state.error = error
    },
    SHOW_ERROR(state, errorMessage) {
      state.error = errorMessage
      // 3秒后自动隐藏错误消息
      setTimeout(() => {
        state.error = null
      }, 3000)
    },
    HIDE_ERROR(state) {
      state.error = null
    }
  },
  actions: {
    async login({ commit }, credentials) {
      commit('SET_LOADING', true)
      try {
        const response = await axios.post('/api/auth/login', credentials)
        const { token, user } = response.data
        localStorage.setItem('token', token)
        axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
        commit('SET_USER', user)
        commit('SET_LOADING', false)
        return user
      } catch (error) {
        commit('SET_ERROR', error.response?.data?.message || '登录失败')
        commit('SET_LOADING', false)
        throw error
      }
    },
    async register({ commit }, userData) {
      commit('SET_LOADING', true)
      try {
        const response = await axios.post('/api/auth/register', userData)
        const { token, user } = response.data
        localStorage.setItem('token', token)
        axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
        commit('SET_USER', user)
        commit('SET_LOADING', false)
        return user
      } catch (error) {
        commit('SET_ERROR', error.response?.data?.message || '注册失败')
        commit('SET_LOADING', false)
        throw error
      }
    },
    async logout({ commit }) {
      try {
        // 如果需要向服务器发送登出请求，可以在这里添加
        // await axios.post('/api/auth/logout')
        
        // 清除Vuex状态
        commit('LOGOUT')
        
        // 清除本地存储
        localStorage.removeItem('user')
        localStorage.removeItem('token')
        
        // 清除axios的授权头
        delete axios.defaults.headers.common['Authorization']
        
        return Promise.resolve()
      } catch (error) {
        commit('SET_ERROR', '登出失败，请稍后再试')
        throw error
      }
    },
    async fetchModels({ commit }) {
      commit('SET_LOADING', true)
      try {
        const response = await axios.get('/api/models')
        commit('SET_MODELS', response.data)
        commit('SET_LOADING', false)
      } catch (error) {
        commit('SET_ERROR', error.response?.data?.message || '获取模型失败')
        commit('SET_LOADING', false)
      }
    },
    async createConversation({ commit }, { modelId, title }) {
      commit('SET_LOADING', true)
      try {
        const response = await axios.post('/api/conversations', {
          modelId,
          title
        })
        const conversation = response.data
        commit('ADD_CONVERSATION', conversation)
        commit('SET_CURRENT_CONVERSATION', conversation)
        commit('SET_LOADING', false)
        return conversation
      } catch (error) {
        commit('SET_ERROR', error.response?.data?.message || '创建会话失败')
        commit('SET_LOADING', false)
        throw error
      }
    },
    async sendMessage({ commit }, { conversationId, message }) {
      commit('SET_LOADING', true)
      try {
        // 添加用户消息
        commit('ADD_MESSAGE', {
          conversationId,
          message: {
            content: message,
            role: 'user',
            timestamp: new Date().toISOString()
          }
        })
        
        // 发送消息到API并获取AI回复
        const response = await axios.post(`/api/conversations/${conversationId}/messages`, {
          content: message
        })
        
        const aiMessage = {
          content: response.data.content,
          role: 'assistant',
          timestamp: new Date().toISOString()
        }
        
        commit('ADD_MESSAGE', {
          conversationId,
          message: aiMessage
        })
        
        commit('SET_LOADING', false)
        return aiMessage
      } catch (error) {
        commit('SET_ERROR', error.response?.data?.message || '发送消息失败')
        commit('SET_LOADING', false)
        throw error
      }
    },
    async fetchUserProfile({ commit }) {
      try {
        const response = await axios.get('/api/auth/user')
        commit('SET_USER', response.data)
        return response.data
      } catch (error) {
        commit('LOGOUT') // 如果获取用户信息失败，可能token已过期，执行登出
        throw error
      }
    }
  },
  getters: {
    user(state) {
      return state.user
    },
    isAuthenticated(state) {
      return state.isAuthenticated
    },
    models(state) {
      return state.models
    },
    conversations(state) {
      return state.conversations
    },
    currentConversation(state) {
      return state.currentConversation
    },
    loading(state) {
      return state.loading
    },
    error(state) {
      return state.error
    }
  }
})
    